package com.forward.uploadapp.activity;

import android.content.Intent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import com.forward.uploadapp.BaseActivity;
import com.forward.uploadapp.R;
import com.forward.uploadapp.adapter.FileDisplayAdapter;
import com.forward.uploadapp.util.FileHelper;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class FileDisplayActivity extends BaseActivity implements AdapterView.OnItemClickListener {
    private List<File> mDatas;
    private ListView mListView;
    private FileDisplayAdapter mAdapter;
    private int mFromWhich;


    public void back(View view) {
        finish();
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_file_display;
    }

    @Override
    public void initView() {
        mListView = (ListView) findViewById(R.id.listview);
    }

    @Override
    public void initData() {
        mFromWhich = getIntent().getIntExtra("from", 0);
        mDatas = new ArrayList<>();
        mAdapter = new FileDisplayAdapter(this, mDatas);
        mListView.setAdapter(mAdapter);
        refreshData();
    }

    @Override
    public void initListener() {
        mListView.setOnItemClickListener(this);
    }

    private void refreshData() {
        List<File> fileList = FileHelper.getFileList(getCurrentPath());
        if (fileList != null) {
            mDatas.clear();
            mDatas.addAll(fileList);
            mAdapter.refresh();
        }
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
        File file = mDatas.get(position);
        if (file.isFile()) {
            Intent intent;
            if (mFromWhich == FROM_APP_INFO_ACTIVITY) {
                intent = new Intent(FileDisplayActivity.this, AppInfoActivity.class);
            } else {
                intent = new Intent(FileDisplayActivity.this, GetJsonActivity.class);
            }
            intent.putExtra("selectFile", file);
            setResult(FROM_FILE_DISPLAY_ACTIVITY, intent);
            finish();
        } else {
            setCurrentPath(file.getAbsolutePath());
            refreshData();
        }
    }
}
